<template>
	<view style="display: flex;" class="gz-search" @touchmove.stop.prevent="moveHandle">
		<image src="/static/img/list-search.svg" alt=""></image>
		<!--放大镜-->
		<input style="flex: 1;" type="text" v-model="searchText" :placeholder="placeholder" @focus="focusHandle" :auto-blur="true" @input="changeHandle($event)">
		<!-- 清空图片 -->

		<image @click="clearText" src="../../static/img/clear-test.svg" class="clear-text" mode="" v-if="searchBtn && clearTextIsShow"></image>

		<view class="btn">
			<slot v-if="!searchBtn" name="option"></slot>
			<view v-if="searchBtn" @click="searchHandle" class="search-text">
				搜索
			</view>
			<view class="mark" @click="hiddenMask" v-show="searchBtn" @touchmove.stop.prevent="moveHandle">
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, nextTick, watch } from 'vue'
	import { onShow } from '@dcloudio/uni-app'
	const props = defineProps({
		value: { type: String, default: null },
		placeholder: { type: String, default: '搜索内容' },
	})

	let searchText = ref('') // 搜索内容

	let clearTextIsShow = ref(false) // 清空按钮是否展示

	// 搜索按钮
	let searchBtn = ref(false)

	function hiddenMask() {
		searchBtn.value = false
	}
	onShow(() => {
		hiddenMask();
	})
	// 监听搜索框中有无内容
	watch(() => searchText.value, () => {
		if (!searchText.value) {
			clearTextIsShow.value = false
		} else {
			clearTextIsShow.value = true
		}
	})
	watch(() => props.value, () => {
		if (props.value === '') {
			searchText.value = ''
		}
	})
	// 禁止页码滚动
	const moveHandle = () => {}

	const emit = defineEmits(['update:value', 'searchHandle'])
	const changeHandle = (e) => emit('update:value', e.detail.value)
	const clearText = () => {
		searchText.value = ''
		emit('update:value', '')
	}

	const searchHandle = () => {
		searchBtn.value = false
		emit('searchHandle')
	}
	// 获得焦点
	const focusHandle = () => {
		searchBtn.value = true
	}

	const backPressHandel = () => {
		if (searchBtn.value) {
			searchBtn.value = false
			return true
		} else {
			return false

		}
	}

	defineExpose({ backPressHandel });
</script>

<style scoped lang="scss">
	.gz-search {
		border-top: 1px solid #FAFBFC;
		display: flex;
		padding: 30rpx;
		box-sizing: border-box;
		align-items: center;
		position: relative;
		height: 90rpx;

		.mark {
			position: absolute;
			width: 100%;
			height: calc(100vh - 180rpx);
			top: 90rpx;
			left: 0;
			z-index: 99;
			background-color: rgba(0, 0, 0, 0.5);
		}

		image {
			width: 26rpx;
			height: 26rpx;
			margin-right: 20rpx;
		}

		input {
			flex-grow: 1;
			margin-right: 20rpx;
		}

		.btn {

			display: flex;
			align-items: center;
			justify-content: space-between;

		}
	}

	.search-text {
		color: $uni-color-primary;
	}

	.clear-text {

		width: 20rpx;
		height: 20rpx;
		// img {
		// 	display: block;
		// }
	}
</style>